﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


namespace SyncServer
{
    public partial class TestDownload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //txtAddress.Text = Request.;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(txtAddress.Text + string.Format("post.aspx?gzip=0&pass={0}&user_code={1}&version={2}", txtPassword.Text, txtUserName.Text, txtVersion.Text));
            byte[] data = System.Text.Encoding.UTF8.GetBytes(txtTableList.Text + "\r\n");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "post";
            request.ContentLength = data.Length;
            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Flush();
            stream.Close();
            System.Net.WebResponse response = request.GetResponse();
            stream = response.GetResponseStream();
            //data = new byte[response.ContentLength];
            //int i = stream.Read(data, 0, data.Length);

            //System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //ms.Write(data, 0, data.Length);
            //ms.Position = 0;
            //data = Decompression(ms);

            lblContent.Text =  Common.Decompress(stream);
            
        }


        /// <summary>
        /// 解压缩数据流
        /// </summary>
        /// <param name="inputStream"></param>
        /// <returns></returns>
        private byte[] Decompression(System.IO.Stream inputStream)
        {
            try
            {

                ICSharpCode.SharpZipLib.GZip.GZipInputStream stream = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(inputStream);

                System.IO.MemoryStream output = new System.IO.MemoryStream();
                byte[] buffer = new byte[4096];
                int read = -1;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, read);

                }
                stream.Close();
                return output.ToArray();
            }
            catch (Exception err)
            {
                throw new Exception("CON_ERR_COMPRESS");
            }
        }
    }
}
